<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title></title>
     <meta name="renderer" content="webkit">
      <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
      <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../static/js/lib/layui/css/layui.css" media="all">
    <style>
        .form-wrap {
            padding: 10px;
        }
    </style>
</head>
<body>
<!-- 新增用户表单 -->
<form id="videofile_form" class="layui-form" style="display: none"
      method="post" enctype="multipart/form-data">
    <div class="layui-form-item" style="display: none">
        <label class="layui-form-label">文件上传</label>
        <!--  name="expertfile" -->
        <div class="layui-input-block">
            <input type="text" id="parentId" name="parentId" >
            <input type="text" id="videoId" name="videoId" >
            <input type="text" id="videoSize" name="videoSize" > <!-- //大小 -->
            <input type="text" id="timeLength" name="timeLength" >   <!-- //时长 -->
            <input type="text" id="videoPath" name="videoPath" >   <!-- //路径-->
                <input type="text" id="type" name="type" >   <!-- //类型 -->
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">视频上传</label>
        <input type="file" id="file" />
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">视频名称</label>
        <div class="layui-input-block">
            <input type="text" name="videoName" lay-verify="title" placeholder="请输入" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">教师名称</label>
        <div class="layui-input-block">
            <input type="text" name="teacherName" lay-verify="title"
                   placeholder="请输入" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">图书简介</label>
        <div class="layui-input-block">
            <textarea name="introduction" id="introduction_textarea"></textarea>
        </div>
    </div> 
    <div class="layui-form-item" style="display: none">
        <div class="layui-input-block">
            <button type=" " class="layui-btn layui-btn-primary"
                    id="deleteclean">重置</button>
        </div>
    </div>
</form>
<div class="layui-progress layui-progress-big" lay-showpercent="true"
     lay-filter="demo" id="progress" style="display: none">
    <div class="layui-progress-bar layui-bg-red" lay-percent="0%"></div>
</div>
<div class="layui-form-item" id="expert_submit" style="display: block">
    <div class="layui-input-block">
        <div class="site-demo-button"
             style="margin-top: 20px; margin-bottom: 0;">
            <!-- data-type="loading"  -->

            <!-- 	 <button id="upload">上传</button> -->
            <button class="layui-btn site-demo-active"  οnclick="window.active.loading();">提交</button>
            <button type=" " class="layui-btn layui-btn-primary" id="cleanbu"
                    οnclick="clean.deleteclean();">重置</button>
        </div>
    </div>
</div>
<script src="../static/js/lib/jquery/jquery.min.js"></script>
<script src="../static/js/lib/layui/layui.js"></script>
    <script src="../static/js/md5.js"></script>
<script type="text/javascript">
    var i = -1;
    var succeed = 0;
    var databgein;  //开始时间
    var dataend;    //结束时间
    var paid;
    var id ;
    var Percent=0;
    var action=false;    //false检验分片是否上传过(默认); true上传文件       
    $(function() {
        var moudle = commonUtil.getRequestParam("moudle");
        $('#videofile_form').show();
        // 展示当前的表单
        switch (moudle) {
            case "expert":
                formObj.expertForm.operType = "insert";
        }
    });
    layui.use(['form','upload','tree', 'layer', 'element', 'table','layedit' ],function() {
        var form = layui.form,
            layer = layui.layer,
            table = layui.table,
            layedit = layui.layedit,
            element = layui.element;
        var $ = layui.jquery,upload = layui.upload;
        id = commonUtil.getRequestParam("id");   //节点Id
        paid = commonUtil.getRequestParam("paid"); //课程ID
        $("#parentId").val(id)
        var introductionEditor = layedit.build('introduction_textarea');
        //触发事件
        window.active = {
            setPercent: function(){
                //设置50%进度
                element.progress('demo', '0%')
            },
            loading : function() {
                var othis = $(this), type = $(this).data('type');
                active[type] ? active[type].call(this,othis) : '';
                $("#progress").attr('style','disply:block');
                var DISABLED = 'layui-btn-disabled';
                if (othis.hasClass(DISABLED))
                    return;
                databgein=new Date();
                var file = $("#file")[0].files[0];  //文件对象
                isUpload(file);
                //模拟loading
                active.setPercent();
                var n = 0, timer = setInterval(function() {
                    // 请求ajax成功之后 将课程列表放到课程下拉框里
                    if (Percent>=100 ) {
                        Percent= 100;
                        clearInterval(timer);
                        othis.removeClass(DISABLED);
                    }
                    element.progress('demo',Percent+"%");
                    // n = n + Math.random()*10|0;
                }, 300 + Math.random() * 1000);
                othis.addClass(DISABLED);
            }
        }
    });
    var clean = {
        deleteclean : function() {
            $("#deleteclean").click()
        }
    }
    function isUpload (file) {
        //构造一个表单，FormData是HTML5新增的
        var form = new FormData();
        var r = new FileReader();
        r.readAsBinaryString(file);
        $(r).load(function(e){
            var bolb = e.target.result;
            var strmd5 = hex_md5(bolb);
            form.append("filemd5", strmd5);
            //Ajax提交
            $.ajax({
                url: "bigfile/isUpload",
                type: "POST",
                data: form,
                async: true,        //异步
                processData: false,  //很重要，告诉jquery不要对form进行处理
                contentType: false,  //很重要，指定为false才能形成正确的Content-Type
                success: function(data){
                    var uuid = data.fileId;
                    if (data.flag == "1") {
                        //没有上传过文件
                        var a = upload(file,uuid,strmd5,data.date);
                    } else if(data.flag == "2") {
                        //已经上传部分
                        upload(file,uuid,strmd5,data.date);
                    }else if(data.flag == "3") {
                        //文件已经上传过
                        Percent=99;
                        update(data);
                    }
                },error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("服务器出错!");
                }
            })
        })
    };
    /*
     * file 文件对象
     * uuid 后端生成的uuid
     * filemd5 整个文件的md5
     * date  文件第一个分片上传的日期(如:20170122)
    */
    function upload (file,uuid,filemd5,date) {
        name = file.name;        //文件名
        size = file.size;        //总大小
        var shardSize = 512 * 1024,    //以1MB为一个分片
            shardCount = Math.ceil(size / shardSize);  //总片数
        if (i > shardCount) {
            i = -1;
            i = shardCount;
        } else {
            if(!action){
                i += 1;  //只有在检测分片时,i才去加1; 上传文件时无需加1
            }
        }
        //计算每一片的起始与结束位置
        var start = i * shardSize,
            end = Math.min(size, start + shardSize);
        //构造一个表单，FormData是HTML5新增的
        var form = new FormData();
        if(!action){
            form.append("action", "check");  //检测分片是否上传
            $("#param").append("action==check ");
        }else{
            form.append("action", "upload");  //直接上传分片
            form.append("data", file.slice(start,end));  //slice方法用于切出文件的一部分
            $("#param").append("action==upload ");
        }
        form.append("uuid", uuid);
        form.append("filemd5", filemd5);
        form.append("date", date);
        form.append("name", name);
        form.append("size", size);
        form.append("total", shardCount);  //总片数
        form.append("index", i+1);        //当前是第几片
        var ssindex = i+1;
        //按大小切割文件段　　
        var data = file.slice(start, end);
        var r = new FileReader();
        r.readAsBinaryString(data);
        $(r).load(function(e){
            var bolb = e.target.result;
            var md5 = hex_md5(bolb);
            form.append("md5", md5);
            //var formData = new FormData(form);
            //Ajax提交
            $.ajax({
                url: "bigfile/upload",
                type: "POST",
                data: form,
                async: false,        //异步
                processData: false,  //很重要，告诉jquery不要对form进行处理
                contentType: false,  //很重要，指定为false才能形成正确的Content-Type
                success: function(data){
                    var fileuuid = data.fileId;
                    var flag = data.flag;
                    //服务器返回该分片是否上传过
                    if(!action){
                        if (flag == "1") {
                            //未上传
                            action = true;
                        } else if(flag == "3") {
                            //已上传
                            action = false;
                            ++succeed;
                        }
                        upload(file,uuid,filemd5,date);
                        //递归调用                　       
                    }else{
                        if(flag == "4") {
                            alert("上传失败，请检查网络");
                            return false;
                        }else if(flag == "5") {
                            $('#videoPath').val(data.path);
                            $('#timeLength').val(data.timelength);
                            $('#videoSize').val(data.size);
                            $('#type').val(data.type);
                            update(data);
                        }
                        //服务器返回分片是否上传成功
                        //改变界面
                        ++succeed;
                        $("#output").text(succeed + " / " + shardCount);
                        var a = GetPercent(succeed,shardCount);
                        if(!a){
                            alert("抱歉，请上传正确视频");
                            return false;
                        }
                        if (i+1 == shardCount) {
                            dataend=new Date();
                        } else {
                            //已上传成功,然后检测下一个分片
                            action=  false;
                            //递归调用                　
                            upload(file,uuid,filemd5,date);
                        }
                    }
                },error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert("抱歉，请重试");
                }
            });
        })
    }
    function update(data){
        var parap = {
            videoCourseId : paid
        }
        var userForm = document.getElementById("videofile_form");
        var formData = new FormData(userForm);
        var url ="";
        if($("#parentId").val()!=""){
            url = "video/update";
        }else{
            layer.alert("请选择节点");
            return;
        }
        var ajaxParam = {
            url : url,
            async : false
        }
        ajaxUtil.submitForm(formData,ajaxParam,function(data) {
            if (data.code = 200) {
                // 关闭当前的表单弹窗 刷新父级页面的数据表格
                var parentHtml = window.parent;
                parentHtml.layer.closeAll();
                parentHtml.refresh(parap);
            }else if(res.code=='400'){
                layer.alert(res.msg);
            }
        })
    }
    function GetPercent(num, total) {
        num = parseFloat(num);
        total = parseFloat(total);
        if (isNaN(num) || isNaN(total)) {
            return false;
        }
        Percent = (Math.round(num / total * 10000) / 100.00);
        return true;
    }
</script>
</body>
</html>
